//
//  MapViewController.swift
//  联付商圈
//
//  Created by zhangqi on 2017/8/18.
//  Copyright © 2017年 lianfu. All rights reserved.
//
import Foundation
import UIKit
import MapKit
import CoreLocation
import Alamofire


@available(iOS 9.0, *)
@objc class MapViewController: BaseViewController {

    
    let locationManager = CLLocationManager()
    //创建一个大头针对象
    let objectAnnotation = MKPointAnnotation()
    var selectedPin:MKPlacemark? = nil
    var currLocation: CLLocation!
    lazy var lat:Double = 0.0
    lazy var long:Double = 0.0
    var locaString = ""
    var tap = UITapGestureRecognizer()
    
    @IBOutlet weak var mapView: MKMapView!
    
    
    @IBAction func over(_ sender: UIButton) {
        
        if lat == 0.0 && long == 0.0 {
            tanchuanger()
        } else if lat != 0.0 && long != 0.0 {
            getshopinfor()
        }
        
    }
    
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.requestLocation()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
            locationManager.requestLocation()
        self.mapView.showsUserLocation = true
        initLocation()
        tap = UITapGestureRecognizer(target: self, action : #selector(maptap))
        tap.numberOfTapsRequired = 1
        mapView.isUserInteractionEnabled = true
        mapView.addGestureRecognizer(tap)
        //self.noticeTop("请点击屏幕确认商店位置", autoClear: true, autoClearTime: 4)
        //NotificationCenter.default.addObserver(self, selector: #selector(self.kbFrameChanged(_:)), name: .UIKeyboardWillChangeFrame, object: nil)
        tanchuang()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    

    func tanchuang(){
        let alertVC = UIAlertController(title: "确认位置", message: "请在地图上点击商店所在位置", preferredStyle: UIAlertControllerStyle.alert)
       
        let acCancel = UIAlertAction(title: "好的", style: UIAlertActionStyle.default) { (UIAlertAction) -> Void in
            return
        }
        alertVC.addAction(acCancel)
        self.present(alertVC, animated: true, completion: nil)
    }
    func tanchuanger(){
        let alertVC = UIAlertController(title: "未选择位置", message: nil, preferredStyle: UIAlertControllerStyle.alert)
        
        let acCancel = UIAlertAction(title: "好的", style: UIAlertActionStyle.default) { (UIAlertAction) -> Void in
            return
        }
        alertVC.addAction(acCancel)
        self.present(alertVC, animated: true, completion: nil)
    }

    
    func maptap(_: UIGestureRecognizer){
        let touchPoint = tap.location(in: self.mapView)
        let xy = self.mapView.convert(touchPoint, toCoordinateFrom: self.mapView)
        
        long = Double(String(format: "%.5f", xy.longitude))!
        lat = Double(String(format: "%.5f", xy.latitude))!
        //设置大头针的显示位置
//        print(long)
//        print(lat)
        //b3 = "&shoplat=\(lat)&shoplng=\(long)&"
        objectAnnotation.coordinate = CLLocation(latitude: xy.latitude, longitude: xy.longitude).coordinate
        self.mapView.addAnnotation(objectAnnotation)
    }
    
    func initLocation() {
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
        locationManager.requestWhenInUseAuthorization()
        
    }
 
    
    
    func getDirections(){
        if let selectedPin = selectedPin {
            let mapItem = MKMapItem(placemark: selectedPin)
            let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving]
            mapItem.openInMaps(launchOptions: launchOptions)
        }
    }


}

@available(iOS 9.0, *)
extension MapViewController : CLLocationManagerDelegate {
    
    
    
 
    
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse {
            locationManager.requestLocation()
            
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //print("hello")
        if let location = locations.first {
            let span = MKCoordinateSpanMake(0.05, 0.05)
            let region = MKCoordinateRegion(center: location.coordinate, span: span)
            mapView.setRegion(region, animated: true)
        }
        currLocation = locations.last!
            self.locationManager.stopUpdatingLocation()
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        //print("error:: \(error)")
    }
    

    
    func getshopinfor(){
        
        param["shoplat"] = "\(lat)"
        param["shoplng"] = "\(long)"
        let urlString = "https://www.beidikeji.com/life/public/jiekou/shopadd?" //+ b1 + b3 + b2
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 45
        manager.request(urlString,method:.post,parameters: param).responseJSON {Request in
            //print(param)
            switch Request.result {
            case .success:
                self.noticeInfo("编辑成功", autoClear: true, autoClearTime: 1)
                self.navigationController?.popToRootViewController(animated: true)
//                let x = UserDefaults.standard.object(forKey: "userInfo") as! NSDictionary
//                let y = x["state"] as! Int
////                let sb = UIStoryboard(name: "Main", bundle:nil)
////                let secondViewController = sb.instantiateViewController(withIdentifier: "NewHomeViewController") as! NewHomeViewController
////                self.navigationController?.popToViewController(secondViewController, animated: true)
//                if y == 1 {
//                    self.poptopre()
//                } else if y == 2 {
//                    self.popto()
//                }
                
            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
            }
        }
    }
    
    
    func popto(){
        self.noticeInfo("编辑成功", autoClear: true, autoClearTime: 1)
        for i in 0 ..< (self.navigationController?.viewControllers.count)! {
            
            if self.navigationController?.viewControllers[i].isKind(of: BusinessCenterViewController.self) == true {
                
                self.navigationController?.popToViewController(self.navigationController?.viewControllers[i] as! BusinessCenterViewController, animated: true)
                break
            }
        }
    }

    func poptopre(){
        self.noticeInfo("编辑成功", autoClear: true, autoClearTime: 1)
        for i in 0 ..< (self.navigationController?.viewControllers.count)! {
            
            if self.navigationController?.viewControllers[i].isKind(of: PersonCenterViewController.self) == true {
                
                self.navigationController?.popToViewController(self.navigationController?.viewControllers[i] as! PersonCenterViewController, animated: true)
                break
            }
        }
    }



}
